# -*- coding: utf-8 -*-
# @Author: XiaoRui
# @FileName: writeXml.py
# @Time: 2021/5/11 15:28
# @Software: PyCharm

import xml.etree.ElementTree as ET


def prettyxml(element, indent, newline, level=0):
    # is element has child element
    if element:
        # element.text is empty
        if element.text is None or element.text.isspace():
            element.text = newline + indent * (level + 1)
        else:
            element.text = newline + indent * (level + 1) + element.text.strip() + newline + indent * (level + 1)
    # Remove the comments from both lines, the Element's text will start on a newline
    # else:
    #     element.text = newline + indent * (level + 1) + element.text.strip() + newline + indent * level
    temp = list(element)
    for subelement in temp:
        # 如果不是list的最后一个元素，说明下一个行是同级别元素的起始，缩进应一致
        if temp.index(subelement) < (len(temp)-1):
            subelement.tail = newline + indent * (level + 1)
        else:
            # 如果是list的最后一个元素， 说明下一行是母元素的结束，缩进应该少一个
            subelement.tail = newline + indent * level
        # 对子元素递归操作
        prettyxml(subelement, indent, newline, level=level+1)


def generate_mapxml(nodes):
    # build root node
    root = ET.Element("collection", attrib={"shelf": "New Arrivals"})
    for i in range(len(nodes)):
        tag = "vertex_interval"
        vertex_interval = ET.SubElement(root, tag+str(i))
        for j in range(len(nodes[i])):
            vertex = ET.SubElement(vertex_interval, "vertex")
            # nodeName
            vertex_name = ET.SubElement(vertex, "vertex_name")
            vertex_name.text = str(nodes[i][j].nodeName)
            # road properties
            vertex_roadOsmId = ET.SubElement(vertex, "vertex_roadOsmId")
            vertex_roadOsmId.text = ','.join('%s' % osm_id for osm_id in nodes[i][j].road_osm_id)
            # road name
            vertex_roadName = ET.SubElement(vertex, "vertex_roadName")
            vertex_roadName.text = nodes[i][j].road_name
            # road type serial number
            vertex_roadType = ET.SubElement(vertex, "vertex_roadType")
            vertex_roadType.text = str(nodes[i][j].road_type)
            # road width
            vertex_roadWide = ET.SubElement(vertex, "vertex_roadWide")
            vertex_roadWide.text = ','.join('%s' % wide for wide in nodes[i][j].road_wide)
            # road speed
            vertex_roadSpide = ET.SubElement(vertex, "vertex_roadSpide")
            vertex_roadSpide.text = ','.join('%s' % spide for spide in nodes[i][j].road_spide)
            # road length
            vertex_roadLength = ET.SubElement(vertex, "vertex_roadLength")
            vertex_roadLength.text = str(nodes[i][j].road_length)
            # road type
            vertex_roadRtype = ET.SubElement(vertex, "vertex_roadRtype")
            vertex_roadRtype.text = nodes[i][j].road_rtype
            # road area
            vertex_roadShapeLeng = ET.SubElement(vertex, "vertex_roadShapeLeng")
            vertex_roadShapeLeng.text = str(nodes[i][j].road_shapeLeng)
            # node coordinates
            vertex_coordinates = ET.SubElement(vertex, "vertex_coordinates")
            vertex_coordinates.text = ','.join('%s' % coordinate for coordinate in nodes[i][j].node_coordinates)
            # node successors
            vertex_childrenNodes = ET.SubElement(vertex, "vertex_childrenNodes")
            vertex_childrenNodes.text = ''
            for k in range(len(nodes[i][j].node_childrenNodes)):
                if len(nodes[i][j].node_childrenNodes) != 0 or len(nodes[i][j].node_childrenNodes) != 1:
                    if k != 0:
                        vertex_childrenNodes.text += ','
                vertex_childrenNodes.text += ','.join('%s' % childCoordinates for childCoordinates in nodes[i][j].node_childrenNodes[k])
    prettyxml(root, '\t', '\n')
    tree = ET.ElementTree(root)
    tree.write('result.xml', encoding='utf-8', xml_declaration=True, short_empty_elements=False)
    print("Generate map xml file successfully!")


def modify_mapxml(xml_path, client_path):
    tree = ET.parse(xml_path)
    root = tree.getroot()

    exam_msg = ET.SubElement(root, "exam_msg")
    race_time = ET.SubElement(exam_msg, "race_time")
    race_time.text = str(client_path["race_time"])

    send_id = ET.SubElement(exam_msg, "send_id")
    send_id.text = str(client_path["send_id"])

    start_point = ET.SubElement(exam_msg, "start_point")
    for key, value in client_path["start_point"].items():
        s_element = ET.SubElement(start_point, key)
        s_element.text = str(value)

    end_point = ET.SubElement(exam_msg, "end_point")
    for key, value in client_path["end_point"].items():
        e_element = ET.SubElement(end_point, key)
        e_element.text = str(value)

    breaks = ET.SubElement(exam_msg, "breaks")
    for i in range(len(client_path["breaks"])):
        temp_break = ET.SubElement(breaks, "break"+str(i))
        for key, value in client_path["breaks"][i].items():
            child_element = ET.SubElement(temp_break, key)
            if isinstance(value, dict):
                for sub_key, sub_value in value.items():
                    sub_child_element = ET.SubElement(child_element, sub_key)
                    sub_child_element.text = str(sub_value)
            else:
                child_element.text = str(value)

    exam_msg.tail = '\n'
    prettyxml(root, '\t', '\n')
    tree.write(xml_path, encoding="utf-8", xml_declaration=True, short_empty_elements=False)
    print("Modify xml file successfully!")
